<template>
  <BasicModal
    v-bind="$attrs"
    :width="modalWidth"
    @register="registerModal"
    title="新增"
    @ok="handleOK"
  >
    <!-- <BasicForm @register="registerForm" /> -->
    <div style="margin-bottom: 20px; display: flex">
      <div style="margin-right: 10px; width: 100px; text-align: right; line-height: 20px"
        >任务类型</div
      >
      <!-- <Select ref="select" v-model:value="selectValue" style="width: 100%">
        <SelectOption value="Video">视频任务</SelectOption>
        <SelectOption value="Chat">私信任务</SelectOption>
      </Select> -->

      <RadioGroup v-model:value="selectValue">
        <Radio value="Video">视频评论任务</Radio>
        <Radio value="Chat">匹配人员任务</Radio>
      </RadioGroup>
    </div>

    <!-- //视频任务列表 -->
    <VideoFrom v-if="selectValue == 'Video'" ref="videoFromRef"></VideoFrom>
    <BasicForm v-else @register="registerFormChat">
      <template #advertisementTemplate>
        <Select
          ref="select"
          v-model:value="advertisementTemplate"
          style="width: 100%"
          @change="fetchTemplateDetail"
          placeholder="请选择模板"
        >
          <!-- <SelectOption value="Video">视频任务</SelectOption>
          <SelectOption value="Chat">私信任务</SelectOption> -->
          <SelectOption v-for="option in templateList" :key="option.id" :value="option.remark">
          </SelectOption>
        </Select>
      </template>
      <!-- template -->
    </BasicForm>
    <div style="padding-bottom: 20px; display: flex">
      <div style="margin-right: 10px; width: 100px; text-align: right; line-height: 30px"
        >选择设备</div
      >
      <Select
        ref="select"
        v-model:value="deviceValue"
        style="width: 100%"
        mode="multiple"
        placeholder="请选择设备"
      >
        <SelectOption v-for="option in deviceList" :key="option.label" :value="option.value">
        </SelectOption>
      </Select>
    </div>
  </BasicModal>
</template>

<script lang="ts" setup>
  import { Tooltip, Select, SelectOption, RadioGroup, Radio, message } from 'ant-design-vue';
  import { ref, computed, unref, onMounted } from 'vue';
  import { BasicModal, useModalInner } from '@/components/Modal';
  import { BasicForm, useForm } from '@/components/Form';
  import { updateVmAPI } from '@/api/demo/mvm';
  import { accountFormChat } from './account.data';
  import VideoFrom from './videoFrom.vue';
  import { getAudiencesListAPI } from '@/api/demo/template';
  import { getdeviceToOwnerAPI } from '@/api/demo/videoList';
  import { createTaskApi } from '@/api/demo/Task';
  defineOptions({ name: 'AccountModal' });
  const isUpdate = ref(true);
  const rowId = ref('');
  const deviceValue = ref([]);
  const selectValue = ref('Video');
  const advertisementTemplate = ref(null);
  const modalWidth = ref('40%'); // 可以是像 600 这样的像素值，或者百分比 '50%'
  const templateList = ref<any[]>([]);
  const deviceList = ref<any[]>([]);
  const emit = defineEmits(['success']);
  const videoFromRef = ref(null); // 定义 ref 来引用子组件
  const links = ref([]);
  //注册表格数据
  // const [registerForm, { resetFields, setFieldsValue, updateSchema, getFieldsValue }] = useForm({
  //   labelWidth: 90,
  //   baseColProps: { span: 24 },
  //   schemas: accountFormSchema,
  //   showActionButtonGroup: false,
  // });

  // 注册私信任务表单  //{ getFieldsValue, setFieldsValue }
  const [registerFormChat, { setFieldsValue }] = useForm({
    labelWidth: 100,
    baseColProps: { span: 24 },
    schemas: accountFormChat,
    showActionButtonGroup: false,
  });
  //注册弹窗数据
  const [registerModal, { setModalProps, closeModal }] = useModalInner(async (data) => {
    setModalProps({ confirmLoading: false });
    isUpdate.value = !!data?.isUpdate;
    links.value = data.links;
    if (unref(isUpdate)) {
      rowId.value = data.record.id;
    }
  });
  async function handleOK() {
    //视频评论任务
    if (selectValue.value == 'Video') {
      // 处理设备标签
      const deviceLabels = deviceValue.value
        .map((deviceId) => {
          const device = deviceList.value.find((d) => d.value === deviceId);
          return device ? device.label : '';
        })
        .filter((label) => label !== ''); // 过滤掉空字符串

      const devicesString = deviceLabels.join(', '); // 将设备标签用逗号拼接起来
      const videoFromData = videoFromRef.value.getData();
      const data = await createTaskApi({
        ...videoFromData,
        links: links.value,
        devices: devicesString,
      });
      message.success("提交完成")
      closeModal();
    }
    // try {
    //   // 获取表单数据并添加 id 字段
    //   const formData = {
    //     id: rowId.value,
    //   };
    //   // 将包含 id 的表单数据传递给 bindAuthorizationCode 函数
    //   let data = await updateVmAPI(formData);
    //   emit('success', data); // 触发 success 事件
    //   closeModal();
    // } finally {
    //   setModalProps({ confirmLoading: false });
    // }
  }

  function fetchTemplateDetail(value, option) {
    try {
      const detail = templateList.value.find((item) => item.id === option.key);
      if (detail) {
        setFieldsValue({
          title: detail.title,
          content: detail.content,
          district: detail.district,
          age: detail.age,
          gender: detail.gender,
          audience: detail.audience,
          interest: detail.interest,
        });
      }
    } catch (error) {
      console.error('获取模板详情失败', error);
    }
  }

  onMounted(async () => {
    try {
      const response = await getAudiencesListAPI();
      templateList.value = response.data; // 假设接口返回的数据结构为 { data: [] }
      // 获取设备管理
      const deviceresponse = await getdeviceToOwnerAPI();
      deviceList.value = deviceresponse.data; // 假设接口返回的数据结构为 { data: [] }
    } catch (error) {
      console.error('获取模板列表失败', error);
    }
  });
</script>
